package com.util;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteExcel {

	public static void main(String[] args) {
		HashMap<String, Object> map1 = new HashMap<String, Object>();
		map1.put("测试结果", "张三");
//		map1.put("age", 50);

//		HashMap<String, Object> map2 = new HashMap<String, Object>();
//		map2.put("province", "北京");
//		map2.put("heigth", 1.68);

		List<HashMap<String, Object>> exp = new ArrayList<>();
		exp.add(map1);
//		exp.add(map2);
		writeToExcel(exp);
	}

	public static void writeToExcel(List<HashMap<String, Object>> mapList) {
		if (mapList == null || mapList.isEmpty()) {
			return;
		}
		try (XSSFWorkbook wb = new XSSFWorkbook(); OutputStream out = new FileOutputStream("G:/WMSApiCase1.xlsx");) {
			XSSFSheet sheet = wb.createSheet();
			int startRowIdx = 0;
			List<String> keyTitle = getKeyTitleByMap(mapList);
			XSSFRow rowHead = sheet.createRow(startRowIdx);
			for (int i = 0; i < keyTitle.size(); i++) {
				XSSFCell cell = rowHead.createCell(i);
				cell.setCellValue(keyTitle.get(i));
			}
			startRowIdx++;

			for (HashMap<String, Object> map : mapList) {
				XSSFRow rowData = sheet.createRow(startRowIdx);
				Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
				for (; iterator.hasNext();) {
					Entry<String, Object> next = iterator.next();
					int idx = keyTitle.indexOf(next.getKey());
					XSSFCell cell = rowData.createCell(idx);
					cell.setCellValue(next.getValue().toString());
				}
				startRowIdx++;
			}
			wb.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static List<String> getKeyTitleByMap(List<HashMap<String, Object>> mapList) {
		Set<String> heads = new HashSet<String>();
		for (HashMap<String, Object> map : mapList) {
			heads.addAll(map.keySet());
		}
		List<String> excelHeads = new ArrayList<String>(heads);
		Collections.sort(excelHeads);
		return excelHeads;
	}

}
